<template>
	<view class="chat-container">
		<view class="box-bg">
			<uni-nav-bar shadow left-icon="left" title="果汁分你一半" :shadow="false" :border="false" @clickLeft="goBack" />
		</view>
		<!-- 消息列表区域 -->
		<scroll-view class="message-list">
			<view v-for="(msg, index) in messages" :key="index">
				<view v-if="shouldShowTime(index)" class="time">
					{{ formatTime(msg.time) }}
				</view>
				<view :class="['message-item', msg.sender]">
					<image class="avatar" :src="msg.sender === 'user' ? 
						'https://cdn8.axureshop.com/demo2024/2251242/images/%E7%A7%81%E4%BF%A1%E8%AF%A6%E6%83%85/u2461.svg'
						: 'https://cdn8.axureshop.com/demo2024/2251242/images/%E6%99%AF%E7%82%B9%E4%B8%BB%E9%A1%B5/u632.svg'" />
					<view class="bubble">
						<text class="content">{{ msg.content }}</text>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 输入框区域 -->
		<view class="input-area">
			<input class="input" v-model="inputText" placeholder="发消息..." @confirm="sendMessage" :focus="autoFocus" />
			<view class="sendBtnBox">
				<text v-if="inputText==''" class="sendBtn">发送</text>
				<button v-else class="send-btn" @click="sendMessage">发送</button>

			</view>

		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		nextTick
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'

	// 响应式数据
	const inputText = ref('')
	const messages = reactive([])
	const scrollTop = ref(0)
	const autoFocus = ref(false)
	const showBtn = ref(true)
	// 模拟机器人回复
	const getRobotReply = (msg) => {
		const replies = [
			'我在的亲，请问有什么需要帮助的吗？',
		]
		return replies[Math.floor(Math.random() * replies.length)]
	}

	const goBack = () => {
		uni.navigateBack({
			delta: 1
		})
	}
	const showSendBtn = () => {
		console.log(123456);
		if (!inputText.value.trim()) {
			showBtn.value != showBtn.value
		} else {
			showBtn.value != showBtn.value
		}
	}
	// 发送消息
	const sendMessage = async () => {
		if (!inputText.value.trim())
			return
		// 用户消息
		messages.push({
			content: inputText.value.trim(),
			time: Date.now(),
			sender: 'user'
		})

		// 清空输入框
		const temp = inputText.value
		inputText.value = ''
		autoFocus.value = true

		// 滚动到底部
		await nextTick()
		scrollToBottom()

		// 模拟机器人回复（1秒延迟）
		setTimeout(() => {
			messages.push({
				content: getRobotReply(temp),
				time: Date.now(),
				sender: 'robot'
			})
			scrollToBottom()
		}, 1000)

	}


	// 判断是否需要显示时间
	const shouldShowTime = (index) => {
		if (index === 0) return true; // 第一条消息总是显示时间
		const currentMsg = messages[index];
		const previousMsg = messages[index - 1];
		const timeDiff = currentMsg.time - previousMsg.time; // 计算时间差（毫秒）
		return timeDiff > 120000; // 如果时间差超过两分钟（120,000 毫秒），则显示时间
	};

	// 时间格式化
	const formatTime = (timestamp) => {
		const date = new Date(timestamp)
		return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
	}

	// 滚动到底部
	const scrollToBottom = () => {
		const query = uni.createSelectorQuery()
		query.select('.message-list').boundingClientRect()
		query.select('.message-list').scrollOffset()
		query.exec(res => {
			if (res[0] && res[1]) {
				scrollTop.value = res[1].scrollTop + res[0].height + 1000
			}
		})
	}
</script>

<style lang="scss" scoped>
	.chat-container {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;

		.box-bg {
			height: auto;
			position: fixed;
			width: 100%;
			top: 0;
		}

		.message-list {
			flex: 1;
			padding: 30rpx;
			background-color: #f5f5f5;
			margin: 105rpx 0;

			.time {
				width: 100%;
				text-align: center;
				margin: 20rpx 0;
				color: #ccc;
				font-size: 27rpx;
			}

			.message-item {
				display: flex;
				margin-bottom: 30rpx;
				margin-right: 30rpx;

				&.user {
					flex-direction: row-reverse;

					.bubble {
						background-color: #95ec69;
						margin-right: 20rpx;
					}
				}

				&.robot {
					.bubble {
						background-color: white;
						margin-left: 20rpx;
					}
				}

				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 8rpx;
				}

				.bubble {
					max-width: 500rpx;
					padding: 20rpx;
					border-radius: 10rpx;
					position: relative;

					.content {
						font-size: 28rpx;
						color: #333;
						white-space: normal;
						/* 允许换行 */
						word-wrap: break-word;
						/* 允许长单词或 URL 换行 */
					}

					.time {
						display: block;
						font-size: 20rpx;
						color: #666;
						margin-top: 10rpx;
						text-align: right;
					}
				}
			}
		}

		.input-area {
			width: 100%;
			position: fixed;
			bottom: 0;
			display: flex;
			align-items: center;
			padding: 20rpx;
			background-color: white;
			border-top: 1rpx solid #eee;

			.input {
				flex: 1;
				height: 70rpx;
				padding: 0 20rpx;
				border: none;
				border-radius: 35rpx;
				margin-right: 20rpx;
				background-color: #eee;
			}

			.sendBtnBox {
				width: 140rpx;
				height: 70rpx;
				line-height: 70rpx;
				margin-right: 30rpx;
			}

			.send-btn {
				width: 140rpx;
				height: 70rpx;
				line-height: 70rpx;
				background-color: #07c160;
				color: white;
				border-radius: 35rpx;
				font-size: 28rpx;
				margin-right: 30rpx;
			}

			.sendBtn {
				width: 140rpx;
				height: 70rpx;
				line-height: 70rpx;
				background-color: none;
				color: #ccc;
				// border-radius: 35rpx;
				text-align: center;
				border: none;
				outline: none;
				font-size: 28rpx;
				margin-left: 30rpx;
			}
		}
	}
</style>